package com.example.administrator.jingpingou.fragment;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.administrator.jingpingou.R;
import com.example.administrator.jingpingou.activity.NextThemeActivity;
import com.example.administrator.jingpingou.adapter.ThemeAdapter;
import com.example.administrator.jingpingou.application.MyApplication;
import com.example.administrator.jingpingou.bean.ThemeBean;
import com.example.administrator.jingpingou.config.NetConfig;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qzone.QZone;

/**
 * Created by Administrator on 2016/8/28 0028.
 */
public class ZhuTiFragment extends Fragment implements PlatformActionListener {
    private com.android.volley.RequestQueue mRequestQueue;
    private StringRequest mJsonRequest;
    private List<ThemeBean>  mData;
    private ListView mListView;
    private ThemeAdapter mAdapter;
    private String zid;
    private ImageView mImageAnim,mImageLogin;
    private RelativeLayout mRelativeLayout;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frament_theme,null);
        initView(view);
        initData();
        setData();
        setListener();
        return view;
    }

    private void setListener() {
        mImageLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                showShare();
            }
        });
    }

    private void showShare() {
        ShareSDK.initSDK(getActivity());
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

// 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle("这是我分享的标题");
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("我是分享文本");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");

// 启动分享GUI
        oks.show(getActivity());

    }
    private void setData() {
        initAnim();
        mListView.setAdapter(mAdapter);
    }
    private void initView(View view) {
        mListView = (ListView) view.findViewById(R.id.lv_fragment_theme);
        mImageAnim = (ImageView) view.findViewById(R.id.iv_fragment_next_two);
        mImageLogin = (ImageView) view.findViewById(R.id.iv_fragment_theme_login);
        mRelativeLayout= (RelativeLayout) view.findViewById(R.id.rl_fragment_theme);
    }
    private void initData() {

        mData =new ArrayList<>();
        loadData();
        mAdapter = new ThemeAdapter(mData,getActivity());

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(),NextThemeActivity.class);
                    intent.putExtra("zid",zid);
                    startActivity(intent);
            }
        });
    }


    private void  initAnim(){
        mImageAnim.setBackgroundResource(R.drawable.pig_fly_wait);
        final AnimationDrawable anim = (AnimationDrawable) mImageAnim.getBackground();
        mImageAnim.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                anim.start();
                return true;
            }
        });
        mRelativeLayout.removeView(mImageAnim);
        mListView.setEmptyView(mImageAnim);

    }

    public void loadData(){
        mRequestQueue = MyApplication.getRequestQueue();
        mJsonRequest =new StringRequest(Request.Method.GET, NetConfig.PATH_THEME, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                parseJson(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        mRequestQueue.add(mJsonRequest);
        mJsonRequest.setTag("GET");
    }
    private void parseJson(String response) {
        try {
            JSONObject jsonObject = new JSONObject(response);
            JSONArray data = jsonObject.getJSONArray("data");
            ThemeBean themeBean;
            for (int i = 0; i < data.length(); i++) {
                themeBean = new ThemeBean();
                JSONObject object = data.getJSONObject(i);
//                Log.d("tag", "parseJson: ===Object"+object);
                zid = object.getString("zid");
//                Log.d("tag", "parseJson: =======zid"+zid);
                themeBean.setIphoneimg(object.getString("iphoneimg"));
                themeBean.setTitle(object.getString("title"));
                themeBean.setZid(object.getString("zid"));
                mData.add(themeBean);
//                Log.d("tag", "parseJson: =====list"+list);
            }
            mAdapter.notifyDataSetChanged();

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        // 防止 程序异常退出
        try {
            // 取消网络请求（取消的网络请求，必须是在之前设置了相应的tag的）
            if (mRequestQueue!=null){
                mRequestQueue.cancelAll("GET");
            }
        }catch (Exception e){

        }
    }

    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {

    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {

    }

    @Override
    public void onCancel(Platform platform, int i) {

    }
}
